//
//  HomeView.swift
//  AICleaner
//
//  Created by firefly on 2025/1/17.
//

import SwiftUI

struct HomeView: View {
    @State private var progress: Double = 0.2
    @State private var progressCpu = 0.0
    @State private var memoryUsage = 0.0
    
    let deviceMonitor = DeviceMonitor()
    
    var body: some View {
       NavigationView {
           ZStack(alignment: .bottom) {
               buildContent()
               
               ToolbarView()
           }
           .ignoresSafeArea()
        }
       .onAppear {
           deviceMonitor.startMonitoring(interval: 3) { (tempCpuUsage, tempMemoryUsage) in
               print("cpuUsage",tempCpuUsage)
               print("tempMemoryUsage",tempMemoryUsage)
               progressCpu = tempCpuUsage
               memoryUsage = tempMemoryUsage.rounded()
           }
       }
       .onDisappear {
           // 停止监控
           DispatchQueue.global().asyncAfter(deadline: .now() + 10) {
               deviceMonitor.stopMonitoring()
           }
       }
    }
    
    /// 构建主体内容
    @ViewBuilder func buildContent() -> some View {
        ScrollView {
            VStack(alignment: .leading) {
                
                buildTopView()
                    .padding(.top, UIApplication.shared.currentWindow?.safeAreaInsets.top ?? 0)
                
                ProgressView(value: progress){
                    HStack {
                        Text("5000")
                        +
                        Text(" files ")
                            .foregroundColor(Color.gray)
                        +
                        Text("16.22G")
                        +
                        Text(" storage space waiting to be cleared")
                            .foregroundColor(Color.gray)
                    }
                    .padding(.vertical,3)
                }

                Image("free_trial")
                    .resizable()
                    .scaledToFit()
                    .padding(.vertical,12)
                
                
                buildOptimizedMemory()
                
                buildSecureView()
                
                Spacer()
             }
             .padding()
             .foregroundColor(.white)
        }
        .background(Color.primaryColor)
        .padding(.bottom,88)
    }
    
    /// 构建安全视图
    @ViewBuilder func buildSecureView() -> some View {
        let viewHeight = 120.0
        let vSpacing = 8.0
        SectionHeaderGroup(
            title: "Secure"
        ) {
            VStack {
                Container{
                    HStack(spacing: 16) {
                        VStack(spacing:vSpacing) {
                            Image("wifi")
                            Text("1").font(.title3).bold() + Text(" kb/s")
                            Text("Speed").foregroundColor(.gray)
                        }
                        .frame(height: viewHeight)
                        .padding()
                        .background(Color(hex: "1C1F4A")!)
                        .borderRadius(8)
                        
                        VStack {
                            ProgressView(value: progressCpu/100)
                                .progressViewStyle(
                                    CircularProgressViewStyle(
                                        gradient: LinearGradient(
                                            colors: [Color(hex: "3EEBFF")!, Color(hex: "315DFF")!],
                                            startPoint: .leading,
                                            endPoint: .trailing
                                        )
                                    ){
                                        VStack {
                                            Text(String(Int(progressCpu)))
                                                .font(.title3)
                                                .bold() + Text(" %").foregroundColor(.gray)
                                            
                                            Text("CPU")
                                                .font(.title3)
                                                .bold()
                                        }
                                    }
                                    
                                )
//                                .frame(width: 100, height: 130)
                        }
                        .frame(maxWidth: .infinity)
                        .frame(height: viewHeight)
                        .padding()
                        .background(Color(hex: "1C1F4A")!)
                        .borderRadius(8)
                        
                        VStack(spacing:vSpacing) {
                            Image("memory")
                            Text("\(Int(memoryUsage))").font(.title3).bold() + Text(" MB")
                            Text("RAM")
                        }
                        .frame(height: viewHeight)
                        .padding()
                        .background(Color(hex: "1C1F4A")!)
                        .borderRadius(8)
                    }
                }
                .padding()
                .frame(maxWidth: .infinity)
                .background(Color(hex: "3F4475"))
                .borderRadius(16)
            }
            HStack {
                Container {
                    VStack(alignment: .leading) {
                        GLCell(
                            title: { Text("Equipment").font(.title3) },
                            subtitle: { Text("security") },
                            trailing: { Image("equipment_security") }
                        )
                        .padding(8)
                    
                        Text("Your software")
                            .foregroundColor(.gray)
                            .padding(.horizontal, 8)
                            .font(.subheadline)
                        
                        IconButton.navigation(title: "Analyze")
                        
                    }
                }
                .frame(maxWidth: .infinity,maxHeight: .infinity)
                .background(Color(hex: "1C1F4A")!)
                .borderRadius(8)
                
                    
                
                Container {
                    VStack(alignment: .leading) {
                        GLCell(
                            title: { Text("wifi").font(.title3) },
                            subtitle: { Text("security") },
                            trailing: { Image("wireless") }
                        )
                        .padding(8)
                    
                        Text("Your internet connection")
                            .foregroundColor(.gray)
                            .padding(.horizontal, 8)
                            .font(.subheadline)
                        
                        IconButton.navigation(title: "Analyze")
                        
                    }
                }
                    .frame(maxWidth: .infinity,maxHeight: .infinity)
                    .background(Color(hex: "1C1F4A")!)
                    .borderRadius(8)
            }
            .frame(height: 160)
        }
    }
    
    /// 构建内存优化视图
    @ViewBuilder func buildOptimizedMemory() -> some View {
        let offSetY = 50.0
        SectionHeaderGroup(
            title: "Optimized memory"
        ) {
            HStack {
                // flutter方式
                ZStack(alignment: .top){
                    VStack {
                        Spacer().frame(height: offSetY)
                        Text("Picture cleaning")
                            .padding(.vertical, 4)
                        Text("Clean up duplicate")
                        Text("similar photos")
                        
                        IconButton.navigation(title: "Tidy up")
                            .padding(.bottom, 5)
                    }
                    .frame(maxWidth: .infinity,maxHeight: .infinity)
                    .background(Color(hex: "1C1F4A")!)
                    .borderRadius(8)
                    .padding(.top, 15)
                    
                    Image("picture_cleaning")
                        .font(.title2)
                    
                    
                
                }
//                .background(.green)
                
                
                // swiftUI方式
                ZStack(alignment: .top){
                    VStack {
                        Spacer().frame(height: offSetY)
                        Text("Video cleaning")
                            .padding(.vertical, 4)
                        Text("Organize videos to")
                        Text("save space")
                        
                        IconButton.navigation(title: "Tidy up")
                            .padding(.bottom, 5)
                    }
                    .frame(maxWidth: .infinity,maxHeight: .infinity)
                    .background(Color(hex: "1C1F4A")!)
                    .borderRadius(8)
                    .padding(.top, 15)
                    
                    Image("video_cleaning")
                        .font(.title2)
                }
                
                
            }
            .frame(height: 210)
        }
    }
    
    /// 构建顶部视图
    @ViewBuilder func buildTopView()-> some View {
        HStack {
            Text("AI Cleaner")
               .font(.largeTitle)
            Spacer()
            
            IconButton(text: "PRO",
                       imageName: "star.fill",
                       isSystemIcon: true,
                       direction: .right,
                       margin: 5
             )
                .padding(.horizontal,10)
                .padding(.vertical,4)
                .padding(.trailing, 4)
                .background(.blue)
                .borderRadius(16)
            
            Image("setting")
                .font(.title2)
        }
    }
}

/// toolbar视图
struct ToolbarView: View {
    var body: some View {
        VStack {
            HStack {
                Spacer()
                Button(action: {
                    print("Button 1 tapped")
                }) {
                    IconButton(text: "Battery", imageName: "battery")
                }
                
                Spacer()
                
                Button(action: {
                    print("Button 2 tapped")
                }) {
                    IconButton(text: "Telephone", imageName: "telephone")
                }
                
                Spacer()
                
                Button(action: {
                    print("Button 3 tapped")
                }) {
                    IconButton(text: "Calendar", imageName: "calendar")
                }
                Spacer()
                
                Button(action: {
                    print("Button 3 tapped")
                }) {
                    IconButton(text: "Privacy", imageName: "privacy")
                }
                Spacer()
            }
            Spacer().frame(height: 20)
        }
        .frame(height: 110)
        .background(Color(hex: "252840"))
        .borderRadius(16, corners: [.topLeft, .topRight])
    }
}


#Preview {
    HomeView()
}

struct CircularProgressViewStyle<Content: View>: ProgressViewStyle {
    var strokeWidth: CGFloat = 12
    var gradient: LinearGradient
    
    var backgroundColor: Color = Color(hex:"0E112F")!
    
    var content: (() -> Content)? // 可选内容

    
    func makeBody(configuration: Configuration) -> some View {
        let progress = configuration.fractionCompleted ?? 0
        
        return ZStack {
            Circle()
                .stroke(backgroundColor, lineWidth: strokeWidth)
            
            if let content {
                content()
            }
            
            Circle()
                .trim(from: 0, to: CGFloat(progress))
                .stroke(gradient, style: StrokeStyle(lineWidth: strokeWidth, lineCap: .round))
                .rotationEffect(.degrees(-90)) // 从顶部开始绘制
                .animation(.easeOut, value: progress)
        }
        .padding(strokeWidth / 2)
    }
}
